/**
 * Created by zhangxiaoyu on 16/12/07.
 */
angular.module('hyt.myOrderCtrl',[])

  .controller('OrderListCtrl',function($scope,$filter,$ionicModal,Orders,Storage,$stateParams,RevokeOrder,$ionicLoading,$ionicPopup,$state,SubmitOrder,$window){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    Storage.set('receiveAddress',null);
    Storage.set('shippingAddress',null);
    Storage.set('changeOrder',null);
    $scope.orderSearch={
      parameter:{
        shipperId:userMsg.rows.id,
        orderNo:'',
        CREATETIME_START:'',
        CREATETIME_END:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    Orders.getOrderData($scope.orderSearch);
    $scope.$on('OrderList.Updated', function() {
      $scope.orderData=Orders.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      Orders.getOrderData($scope.orderSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      Orders.getMoreOrderData($scope.orderSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return Orders.hasNextPage();
    };
    var t = new Date();
    var iToDay=t.getDate();
    var iToMon=t.getMonth();
    var iToYear=t.getFullYear();
    var iTDate=new Date(iToYear,iToMon,(iToDay-30));
    $scope.startDate=$filter('date')(iTDate,'yyyy-MM-dd');
    $scope.showStartDate = function() { //选择日期
      var optionsStart = {
        date: iTDate,
        mode: 'date',
        maxDate: new Date($scope.endDate) - 10000
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            iTDate=d;
            $scope.startDate = $filter('date')(iTDate,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.endDate=$filter('date')(new Date(),'yyyy-MM-dd');
    $scope.showEndDate = function(){
      var optionsEnd = {
        date : new Date(),
        mode : 'date',
        minDate: new Date($scope.startDate) - 10000
      };
      datePicker.show(optionsEnd,function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            endTime=d;
            $scope.endDate = $filter('date')(endTime,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.searchOrder=function(){
      $scope.orderSearch.parameter.CREATETIME_START=$scope.startDate;
      $scope.orderSearch.parameter.CREATETIME_END=$scope.endDate;
      //$scope.orderSearch.parameter.ORDER_STATUS=$('#orderState').val();
      //$scope.orderSearch.parameter.ORDER_TYPE=$('#orderType').val();
      Orders.getOrderData($scope.orderSearch);
      $scope.modal.hide();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/myOrder/searchOrder.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.orderRevoke=function(id){
      var revokeOrder={
        id:id,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      var confirmPopup = $ionicPopup.confirm({
        title:'是否撤销订单',
        okText:'是',
        cancelText:'否'
      });
      confirmPopup.then(function(res) {
        if(res){
          RevokeOrder.getRevokeOrder(JSON.stringify(revokeOrder));
          $scope.$on('RevokeOrder.Updated', function() {
            var result=RevokeOrder.getResult();
            if (result.success==true){
              $ionicLoading.show({
                noBackdrop: true,
                template: result.rows,
                duration: 1500
              });
              Orders.getOrderData($scope.orderSearch);
            }
          });
        }
        else {
          return false;
        }
      });
    };
    $scope.orderSubmit=function(id){
      var submitOrder={
        id:id,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      var confirmPopup = $ionicPopup.confirm({
        title:'是否提交订单',
        okText:'是',
        cancelText:'否'
      });
      confirmPopup.then(function(res) {
        if(res){
          SubmitOrder.getSubmitOrder(JSON.stringify(submitOrder));
          $scope.$on('SubmitOrder.Updated', function() {
            var result=SubmitOrder.getResult();
            if (result.success==true){
              $ionicLoading.show({
                noBackdrop: true,
                template: result.rows,
                duration: 1500
              });
              Orders.getOrderData($scope.orderSearch);
            }
          });
        }
        else {
          return false;
        }
      });
    }
    $scope.goDetail=function(id){
      Storage.set('orderId',id);
      $state.go('detailTab.detail',{htmlId:0});
    };
    $scope.changeOrder=function(id){
      $state.go('changeOrder',{id:id});
    };
    $scope.callPhone = function (mobilePhone) {
      var confirmPopup = $ionicPopup.confirm({
        title:mobilePhone,
        okText:'呼叫',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if (res) {
          $window.location.href = "tel:" + mobilePhone;
        }else {

        }
      });
    };
  })
  .controller('OrderDetailCtrl',function($scope,$filter,$ionicModal,OrderDetail,$stateParams,Storage,$state){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var orderDetail={
      id:Storage.get('orderId'),
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    OrderDetail.getOrderDetail(JSON.stringify(orderDetail));
    $scope.$on('OrderDetail.Updated', function() {
      $scope.orderDetail=OrderDetail.getResult().rows;
      $scope.imgData=$scope.orderDetail.pictureInfo;
      switch ($scope.orderDetail.paymentSwitch){
        case '0' :
          $scope.paymentSwitch = '现付';
          break;
        case '1' :
          $scope.paymentSwitch = '到付';
          break;
        case '2' :
          $scope.paymentSwitch = '回付';
          break;
        case '3' :
          $scope.paymentSwitch = '月结';
          break;
        case '4' :
          $scope.paymentSwitch = '货到打卡';
          break;
        case '5' :
          $scope.paymentSwitch = '欠付';
          break;
        case '6' :
          $scope.paymentSwitch = '代扣';
          break;
        case '7' :
          $scope.paymentSwitch = '多笔付';
          break;
        default :
          break;
      }
      switch ($scope.orderDetail.orderInfo.orderStatus){
        case '0' :
          $scope.orderStatus = '待受理';
          break;
        case '1' :
          $scope.orderStatus = '已受理';
          break;
        case '2' :
          $scope.orderStatus = '已拒绝';
          break;
        case '3' :
          $scope.orderStatus = '已作废';
          break;
        case '4' :
          $scope.orderStatus = '已撤销';
          break;
        default :
          break;
      }
      switch ($scope.orderDetail.pickupSwitch){
        case '0' :
          $scope.pickupSwitch = '是';
          break;
        case '1' :
          $scope.pickupSwitch = '否';
          break;
        default :
          break;
      }
      switch ($scope.orderDetail.insureSwitch){
        case '0' :
          $scope.insureSwitch = '是';
          break;
        case '1' :
          $scope.insureSwitch = '否';
          break;
        default :
          break;
      }
      switch ($scope.orderDetail.receiptSwitch){
        case '0' :
          $scope.receiptSwitch = '是';
          break;
        case '1' :
          $scope.receiptSwitch = '否';
          break;
        default :
          break;
      }
      $scope.showloading=false;
    });
    //点击图片放大
    $scope.showBigImage = function (imageName) {  //传递一个参数（图片的URl）
      $scope.Url = imageName;                   //$scope定义一个变量Url，这里会在大图出现后再次点击隐藏大图使用
      $('.tabs').removeClass("show").addClass("hide");
      $('#bigImg').show(500);
    };
    $scope.hideBigImage = function () {
      $('#bigImg').hide(500);
      $('.tabs').removeClass("hide").addClass("show");
    };
    $scope.goBack=function(){
      if ($stateParams.htmlId==0){
        $state.go('myOrder');
      }else if ($stateParams.htmlId==1){
        $state.go('myReceipt');
      }else if ($stateParams.htmlId==2){
        $state.go('tab.workbench');
      }
    }
  })
  .controller('OrderProcessCtrl',function($scope,$filter,$ionicModal,OrderRecord,Storage,$stateParams,$state){
    var loginMsg=Storage.get('user');
    $scope.showloading=true;
    var orderRecord={
      orderId:Storage.get('orderId'),
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    OrderRecord.getOrderRecord(JSON.stringify(orderRecord));
    $scope.$on('OrderRecord.Updated', function() {
      var orderProcess=OrderRecord.getResult().rows;
      $scope.showloading=false;
      if (orderProcess!=undefined){
        $scope.processFirst=orderProcess[0];
      }else {
        $scope.processFirst=null;
      }
      var processData=[];
      var j;
      for(var i=1;i<orderProcess.length;i++){
        j=i-1;
        processData[j]=orderProcess[i];
      }
      $scope.processData=processData;
    });
    $scope.goBack=function(){
      if ($stateParams.htmlId==0){
        $state.go('myOrder');
      }else if ($stateParams.htmlId==1){
        $state.go('myReceipt');
      }else if ($stateParams.htmlId==2){
        $state.go('tab.workbench');
      }
    }
  })
  .controller('ChangeOrderCtrl',function($scope,$filter,$ionicModal,Storage,AddOrder,$ionicPopup,PaymentMethod,DeptByDivision,$ionicLoading,$timeout,$state,PackType,$stateParams,DefaultAddress,$ionicActionSheet,$cordovaCamera,$cordovaImagePicker,$window,OrderDetail){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    $scope.showloading=true;
    var orderDetail={
      id:$stateParams.id,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    if (Storage.get('changeOrder')!=null){
      $scope.order=Storage.get('changeOrder');
      if (Storage.get('receiveAddress')!=null){
        var receiveAddress=JSON.parse(Storage.get('receiveAddress'));
        $scope.order.consigneeName=receiveAddress.CUSTOMER_NAME;
        $scope.order.consigneePhone=receiveAddress.CUSTOMER_PHONE;
        $scope.order.consigneeProvince=receiveAddress.CONSIGNEE_PROVINCE;
        $scope.order.consigneeCity=receiveAddress.CONSIGNEE_CITY;
        $scope.order.consigneeDistrict=receiveAddress.CONSIGNEE_DISTRICT;
        $scope.order.consigneeAddress=receiveAddress.CUSTOMER_ADDRESS;
        $scope.order.consigneeDetailAddress=receiveAddress.CONSIGNEE_PROVINCE_NAME+receiveAddress.CONSIGNEE_CITY_NAME+receiveAddress.CONSIGNEE_DISTRICT_NAME+receiveAddress.CUSTOMER_ADDRESS;
      }
      if (Storage.get('shippingAddress')!=null){
        var shipperAddress=JSON.parse(Storage.get('shippingAddress'));
        $scope.order.consignorName=shipperAddress.CUSTOMER_NAME;
        $scope.order.consignorPhone=shipperAddress.CUSTOMER_PHONE;
        $scope.order.consignorProvince=shipperAddress.CONSIGNEE_PROVINCE;
        $scope.order.consignorCity=shipperAddress.CONSIGNEE_CITY;
        $scope.order.consignorDistrict=shipperAddress.CONSIGNEE_DISTRICT;
        $scope.order.consignorAddress=shipperAddress.CUSTOMER_ADDRESS;
        $scope.order.consignorDetailAddress=shipperAddress.CONSIGNEE_PROVINCE_NAME+shipperAddress.CONSIGNEE_CITY_NAME+shipperAddress.CONSIGNEE_DISTRICT_NAME+shipperAddress.CUSTOMER_ADDRESS;
      }
      $scope.showloading=false;
      $timeout(function(){
        $('#GOODS_PACK').val($scope.order.goodsInfo.goodsPack);
        $('#DELIVERY_TYPE').val($scope.order.deliveryType);
        $('#paymentMethod').val($scope.order.paymentSwitch);
        $('#weight').val(parseFloat($scope.order.goodsInfo.weight).toFixed(2));
        $('#volume').val(parseFloat($scope.order.goodsInfo.volume).toFixed(2));
        $('#AGENCY_FUND').val(parseFloat($scope.order.costMap.AGENCY_FUND).toFixed(2));
        $('#DECLARE_VALUE').val(parseFloat($scope.order.costMap.DECLARE_VALUE).toFixed(2));
      },300);
    }else {
      OrderDetail.getOrderDetail(JSON.stringify(orderDetail));
    }
    $scope.$on('OrderDetail.Updated', function() {
      var orderDetail = OrderDetail.getResult().rows;
      $scope.order={
        customerId:userMsg.rows.id, //用户id
        belongId:orderDetail.belongId, //物流公司id
        companyName:orderDetail.companyName,
        orderId:$stateParams.id, //订单ID，为空是新增订单，不为空是编辑订单
        orderType:'0',
        consignorName:orderDetail.consignorName, //发货人姓名
        consignorPhone:orderDetail.consignorPhone, //发货人电话
        consignorProvince:orderDetail.consignorProvince,//发货人省id
        consignorCity:orderDetail.consignorCity,//发货人市id
        consignorDistrict:orderDetail.consignorDistrict,//发货人区id
        consignorAddress:orderDetail.consignorAddress, //发货人地址
        consignorDetailAddress:orderDetail.consignorProvinceName+orderDetail.consignorCityName+orderDetail.consignorDistrictName+orderDetail.consignorAddress,//发货人详细地址
        consigneeName:orderDetail.consigneeName, //收货人名称
        consigneePhone:orderDetail.consigneePhone, //收货人电话
        consigneeProvince:orderDetail.consigneeProvince,//收货人省id
        consigneeCity:orderDetail.consigneeCity,//收货人市id
        consigneeDistrict:orderDetail.consigneeDistrict,//收货人区id
        consigneeAddress:orderDetail.consigneeAddress, //收货人地址
        consigneeDetailAddress:orderDetail.consigneeProvinceName+orderDetail.consigneeCityName+orderDetail.consignorDistrictName+orderDetail.consigneeAddress,//收货人详细地址
        deliveryType:orderDetail.deliveryType, //送货方式
        paymentSwitch:orderDetail.paymentSwitch, //付款方式
        receiptSwitch:orderDetail.receiptSwitch, //是否签回单
        isReceipt:'',
        pickupSwitch:orderDetail.pickupSwitch, //是否提货
        isPickup:'',
        insureSwitch:orderDetail.insureSwitch, //是否投保
        isInsure:'',
        remark:orderDetail.remark, //备注
        costMap:{
          AGENCY_FUND:orderDetail.costMap.AGENCY_FUND, //代收货款
          DECLARE_VALUE:orderDetail.costMap.DECLARE_VALUE //声明价值
        },
        goodsInfo:orderDetail.goodsInfo,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      $scope.showloading=false;
      $timeout(function(){
        $('#GOODS_PACK').val($scope.order.goodsInfo.goodsPack);
        $('#DELIVERY_TYPE').val($scope.order.deliveryType);
        $('#paymentMethod').val($scope.order.paymentSwitch);
        if ($scope.order.pickupSwitch=='0'){
          $scope.order.isPickup=true;
        }else {
          $scope.order.isPickup=false;
        }
        if ($scope.order.insureSwitch=='0'){
          $scope.order.isInsure=true;
        }else {
          $scope.order.isInsure=false;
        }
        if ($scope.order.receiptSwitch=='0'){
          $scope.order.isReceipt=true;
        }else {
          $scope.order.isReceipt=false;
        }
      },300);
    });
    $scope.effectiveNumber=function(val,bs){
      if (bs==0){
        $('#weight').val(parseFloat(val).toFixed(2));
      }else if (bs==1){
        $('#volume').val(parseFloat(val).toFixed(2));
      }else if (bs==2){
        $('#AGENCY_FUND').val(parseFloat(val).toFixed(2));
      }else if (bs==3){
        $('#DECLARE_VALUE').val(parseFloat(val).toFixed(2));
      }
    };
    $scope.goChooseReceive=function(){
      $state.go('receiveAddress',{isChoose:1,htmlId:1});
      $scope.order.goodsInfo.goodsPack=$("#GOODS_PACK option:selected").val();
      $scope.order.deliveryType=$("#DELIVERY_TYPE option:selected").val();
      $scope.order.paymentSwitch=$("#paymentMethod option:selected").val();
      $timeout(function(){
        Storage.set('changeOrder',$scope.order);
      },160);
    };
    $scope.goChooseShipper=function(){
      $state.go('shipperAddress',{isChoose:1,htmlId:1});
      $scope.order.goodsInfo.goodsPack=$("#GOODS_PACK option:selected").val();
      $scope.order.deliveryType=$("#DELIVERY_TYPE option:selected").val();
      $scope.order.paymentSwitch=$("#paymentMethod option:selected").val();
      $timeout(function(){
        Storage.set('changeOrder',$scope.order);
      },160);
    };
    //物流公司
    $scope.companySearch={
      province:Storage.get('gpsProvince'),
      city:Storage.get('gpsCity'),
      county:Storage.get('gpsArea'),
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    DeptByDivision.getDeptByDivision(JSON.stringify($scope.companySearch));
    $scope.$on('DeptByDivision.Updated', function() {
      $scope.companyData=DeptByDivision.getResult().rows;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      DeptByDivision.getDeptByDivision(JSON.stringify($scope.companySearch));
      $scope.$broadcast('scroll.refreshComplete');
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/addOrder/chooseCompany.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.chooseComp=function(id,companyName){
      $scope.order.belongId=id;
      $scope.order.companyName=companyName;
      $scope.modal.hide();
    };
    //付款方式
    var paymentMethod={
      type:'payment_method',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    if (Storage.get('paymentMethods')!=null){
      $scope.paymentMethods=Storage.get('paymentMethods');
    }else {
      PaymentMethod.getPaymentMethod(JSON.stringify(paymentMethod));
    }
    $scope.$on('PaymentMethod.Updated', function() {
      var result=PaymentMethod.getResult();
      if (result.success==true){
        $scope.paymentMethods=result.rows;
      }
    });
    //包装方式
    var packType={
      type:'pack_type',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    if (Storage.get('packTypes')!=null){
      $scope.packTypes=Storage.get('packTypes');
    }else {
      PackType.getPackType(JSON.stringify(packType));
    }
    $scope.$on('PackType.Updated', function() {
      var result=PackType.getResult();
      if (result.success==true){
        $scope.packTypes=result.rows;
      }
    });

    //保存修改
    function  changeOrder(){
      $scope.order.goodsInfo.goodsPack=$("#GOODS_PACK option:selected").val();
      $scope.order.deliveryType=$("#DELIVERY_TYPE option:selected").val();
      $scope.order.paymentSwitch=$("#paymentMethod option:selected").val();
      //是否投保
      if ($scope.order.isInsure){
        $scope.order.insureSwitch='0';
      }else {
        $scope.order.insureSwitch='1';
      }
      //是否提货
      if ($scope.order.isPickup){
        $scope.order.pickupSwitch='0';
      }else {
        $scope.order.pickupSwitch='1';
      }
      //是否签单
      if ($scope.order.isReceipt){
        $scope.order.receiptSwitch='0';
      }else {
        $scope.order.receiptSwitch='1';
      }
      if ($scope.order.goodsInfo.goodsName==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请填写货物名称",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else if ($scope.order.goodsInfo.pieces==null){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请填写货物件数",
          duration: 1500
        });
        $("#save").attr("disabled",false);
      }else {
        AddOrder.getAddOrder($scope.order);
      }
    }
    $scope.changeOrder=function(){
      $("#save").attr("disabled",true);
      changeOrder();
      $scope.$on('AddOrder.Updated', function() {
        var result=AddOrder.getResult();
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: "保存成功",
            duration: 1500
          });
          $state.go('myOrder');
        }
      });
    };
    $scope.callPhone = function (mobilePhone) {
      var confirmPopup = $ionicPopup.confirm({
        title:mobilePhone,
        okText:'呼叫',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if (res) {
          $window.location.href = "tel:" + mobilePhone;
        }else {

        }
      });
    };
  });
